package com.bdqn.config;

import com.bdqn.pojo.Right;
import com.bdqn.service.RightService;
import com.bdqn.service.RoleService;
import com.bdqn.shiro.MyShiroRealm;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * ShiroConfig
 *
 * @author LILIBO
 * @since 2024-10-15
 */
@Configuration
public class ShiroConfig {

    @Resource
    private RightService rightService;

    // 注入Redis参数，从application.propterties获取
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;

    @Resource
    private RoleService roleService;

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        // 散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        // 散列的次数，比如散列两次，相当于 md5(md5(""));
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }


    @Bean(name="shiroDialect")
    public ShiroDialect shiroDialect() {
        // thymeleaf页面上使用shiro标签
        return new ShiroDialect();
    }


    /**
     * 开启Shiro注解
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    /**
     * 开启aop注解支持
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(port);
        redisManager.setPassword(password);
        redisManager.setTimeout(timeout);
        return redisManager;
    }

    public RedisCacheManager redisCacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        // 缓存名称
        redisCacheManager.setPrincipalIdFieldName("userName");
        // 缓存有效时间
        redisCacheManager.setExpire(1800);
        return redisCacheManager;
    }

    /**
     * 回话操作
     */
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }

    /**
     * 回话管理
     */
    public DefaultWebSecurityManager defaultWebSecurityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());///////////////////////////////////////////////
        return securityManager;
    }

    /**
     * 自定义Realm（基于数据库）
     */
    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm shiroRealm = new MyShiroRealm();
        // 设置启用缓存，并设置缓存名称
        shiroRealm.setCachingEnabled(true);
        shiroRealm.setAuthenticationCachingEnabled(true);
        // 设置凭证（密码）匹配器
        shiroRealm.setAuthenticationCacheName("authenticationCache");
        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return shiroRealm;
    }

    /**
     * 安全管理器SecurityManager
     */
    @Bean
    public SecurityManager securityManager() {
        // 安全管理器 SecurityManager
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 注入自定义的Realm
        securityManager.setRealm(myShiroRealm());
        // 注入缓存管理器
        securityManager.setCacheManager(redisCacheManager());
        // 注入会话管理器 Shiro2.0.1新版本需要SecurityUtils设置SecurityManager，否则报错（org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code）
        SecurityUtils.setSecurityManager(securityManager);
        return securityManager;
    }

    /**
     * Shiro过滤器：权限验证
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager) {
        // Shiro过滤器：权限验证
        ShiroFilterFactoryBean shiroFilterFactory = new ShiroFilterFactoryBean();
        // 注入SecurityManager
        shiroFilterFactory.setSecurityManager(securityManager);
        // 权限验证：使用 Filter 控制资源(URL)的访问
        shiroFilterFactory.setLoginUrl("/login"); // 登录页面URL
        shiroFilterFactory.setSuccessUrl("/main"); // 登录成功URL
        shiroFilterFactory.setUnauthorizedUrl("/403"); // 没有权限跳转403页面

        // 权限配置集合，必须使用LinkedHashMap(有序集合)
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        // 静态资源授权
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/localcss/**", "anon");
        filterChainDefinitionMap.put("/localjs/**", "anon");

        // API接口请求授权
        filterChainDefinitionMap.put("/api/**", "anon");

        // 登录退出页面设置
        filterChainDefinitionMap.put("/login", "anon"); // 点击登录按钮时放行
        filterChainDefinitionMap.put("/logout", "logout"); // 点击退出按钮时放行

        List<Right> rights = rightService.findAllRights();
        for (Right right : rights) {
            if (right.getRightUrl() != null && !right.getRightUrl().trim().equals("")) {
                // 如果权限URL不为空，则添加到权限配置集合中
                filterChainDefinitionMap.put(right.getRightUrl(), "perms[" + right.getRightCode() + "]");
            }
        }


        // 配置需要特定权限才能访问的资源(URL)
        // 静态授权：包括全部需要特定权限才能访问的资源(URL)
        filterChainDefinitionMap.put("/user/list", "perms[用户列表]");
        filterChainDefinitionMap.put("/user/add", "perms[用户添加]");
        filterChainDefinitionMap.put("/user/edit", "perms[用户编辑]");
        filterChainDefinitionMap.put("/user/del", "perms[用户删除]");
        // 省略其他

        // 配置认证访问：其他资源(URL)必须认证通过才能访问
        filterChainDefinitionMap.put("/**", "authc"); // 必须放在过滤器链的最后面
        shiroFilterFactory.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactory;
    }

}
